<template>
  <div class="chat-header">
    <div class="avatar-box">
      <img :src="currentContact?.avatar || defaultAvatar" class="avatar" />
    </div>
    <div class="info">
      <div class="top-row">
        <div class="name-container">
          <span v-if="!isEditing" class="name" @click="startEditing">
            {{ currentContact?.name || "--" }}
            <el-icon v-if="!isColleagueChat" class="edit-icon"><Edit /></el-icon>
          </span>
          <div v-else class="edit-name-input">
            <el-input ref="nameInputRef" v-model="editingName" size="small">
              <template #suffix>
                <el-icon class="save-name-btn" @click.stop="saveCustomerName"><Check /></el-icon>
              </template>
            </el-input>
          </div>
        </div>
        <el-tag v-if="isColleagueChat" size="small" type="info" class="colleague-tag">
          同事会话
        </el-tag>
      </div>
      <div class="bottom-row">
        <span class="time">{{ formatLastTime(currentContact?.sendTime) }}</span>
      </div>
    </div>
    <div class="actions">
      <el-popover
        placement="bottom"
        :width="200"
        trigger="click"
        popper-class="notification-popover"
      >
        <template #reference>
          <el-button size="small" :icon="Bell" circle></el-button>
        </template>
        <div class="notification-settings">
          <h4>通知设置</h4>
          <div class="setting-item">
            <span>声音提醒</span>
            <el-switch v-model="soundEnabled" @change="toggleSound" />
          </div>
          <div class="setting-item">
            <span>桌面通知</span>
            <el-switch v-model="notificationEnabled" @change="toggleNotification" />
          </div>
          <div v-if="notificationEnabled && !hasNotificationPermission" class="setting-tip">
            <el-alert type="warning" :closable="false" size="small" show-icon>
              <span>需要授权通知权限</span>
              <el-button type="primary" link size="small" @click="requestNotificationPermission">
                请求权限
              </el-button>
            </el-alert>
          </div>
        </div>
      </el-popover>
      <el-dropdown v-if="currentContact && !isColleagueChat" @command="handleTransfer">
        <el-button size="small" type="primary" plain>
          转接会话
          <el-icon class="el-icon--right"><arrow-down /></el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item v-for="agent in availableAgents" :key="agent.id" :command="agent.id">
              {{ agent.nickname || agent.username }}-
              <span :class="agent.isOnline === 1 ? 'status-online' : 'status-offline'">
                {{ agent.isOnline === 1 ? "在线" : "离线" }}
              </span>
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from "vue";
import { ArrowDown, Edit, Check, Bell } from "@element-plus/icons-vue";
import defaultAvatar from "@/assets/icons/header-icon.png";
import ChatAPI from "@/api/chat.api";
import { formatDateTimeAuto } from "@/utils/date";
import { useUserStoreHook } from "@/store/modules/user.store";
import { ElMessage } from "element-plus";
import SoundService from "@/utils/notification";

const userStore = useUserStoreHook();
const props = defineProps({
  currentContact: Object,
  isColleagueChat: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["transfer", "endSession", "update:customerName"]);
const availableAgents = ref([]);

// 客户名称编辑状态
const isEditing = ref(false);
const editingName = ref("");
const nameInputRef = ref(null);

// 通知相关状态
const soundEnabled = ref(true);
const notificationEnabled = ref(true);
const hasNotificationPermission = ref(false);

// 监听当前联系人变化，重置编辑状态
watch(
  () => props.currentContact,
  () => {
    isEditing.value = false;
    editingName.value = props.currentContact?.name || "";
  },
  { immediate: true }
);

// 开始编辑名称
function startEditing() {
  if (props.isColleagueChat || !props.currentContact) return;

  editingName.value = props.currentContact.name || "";
  isEditing.value = true;

  // 下一个渲染周期后聚焦输入框
  nextTick(() => {
    nameInputRef.value?.focus();
  });
}

// 保存客户名称
async function saveCustomerName() {
  if (!isEditing.value || !props.currentContact) return;

  const newName = editingName.value.trim();
  if (!newName) {
    ElMessage.warning("客户名称不能为空");
    editingName.value = props.currentContact.name || "";
    isEditing.value = false;
    return;
  }

  // 如果名称没有变化，直接退出编辑模式
  if (newName === props.currentContact.name) {
    isEditing.value = false;
    return;
  }

  try {
    await ChatAPI.updateSessionName(props.currentContact.id, newName);
    ElMessage.success("客户名称修改成功");

    // 通知父组件更新联系人列表
    emit("update:customerName", {
      sessionId: props.currentContact.id,
      customerName: newName,
    });

    isEditing.value = false;
  } catch (error) {
    console.error("修改客户名称失败", error);
    ElMessage.error("修改客户名称失败");
  }
}

// 格式化最后时间
function formatLastTime(time) {
  return formatDateTimeAuto(time);
}

// 获取可用客服列表
async function fetchAvailableAgents() {
  try {
    const res = await ChatAPI.getAvailableAgents();
    let agentList = res.list || [];

    // 过滤掉自己
    const currentUserId = userStore.userInfo.userId;
    agentList = agentList.filter((agent) => agent.id !== currentUserId);
    agentList.sort((a, b) => b.isOnline - a.isOnline);
    availableAgents.value = agentList;
  } catch (error) {
    console.error("获取可用客服列表失败", error);
  }
}

// 处理转接操作
function handleTransfer(agentId) {
  if (props.currentContact && !props.isColleagueChat) {
    emit("transfer", agentId);
  }
}

// 切换声音
function toggleSound(enabled) {
  SoundService.toggleSound(enabled);
  localStorage.setItem("chat_sound_enabled", enabled ? "1" : "0");
}

// 切换通知
function toggleNotification(enabled) {
  SoundService.toggleNotification(enabled);
  localStorage.setItem("chat_notification_enabled", enabled ? "1" : "0");

  if (enabled) {
    requestNotificationPermission();
  }
}

// 请求通知权限
async function requestNotificationPermission() {
  const granted = await SoundService.checkNotificationPermission();
  hasNotificationPermission.value = granted;

  if (!granted && notificationEnabled.value) {
    ElMessage.warning("请在浏览器设置中允许通知权限");
  }
}

// 加载通知设置
function loadNotificationSettings() {
  // 加载声音设置
  const soundSetting = localStorage.getItem("chat_sound_enabled");
  if (soundSetting !== null) {
    soundEnabled.value = soundSetting === "1";
    SoundService.toggleSound(soundEnabled.value);
  }

  // 加载通知设置
  const notificationSetting = localStorage.getItem("chat_notification_enabled");
  if (notificationSetting !== null) {
    notificationEnabled.value = notificationSetting === "1";
    SoundService.toggleNotification(notificationEnabled.value);
  }

  // 检查通知权限
  SoundService.checkNotificationPermission().then((granted) => {
    hasNotificationPermission.value = granted;
  });
}

onMounted(() => {
  fetchAvailableAgents();
  loadNotificationSettings();
});
</script>

<style scoped>
.chat-header {
  display: flex;
  align-items: center;
  padding: 8px 2px;
  border-radius: 8px;
  transition: background 0.2s;
  width: 100%;
  height: 60px;
  border-bottom: 1px solid #eee;
  background: #fff;
  padding: 0 10px;
}
.avatar-box {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
  overflow: hidden;
}
.avatar {
  width: 100%;
  height: 100%;
}
.info {
  flex: 1;
  min-width: 0;
}
.top-row {
  display: flex;
  align-items: center;
}
.name-container {
  display: flex;
  align-items: center;
  margin-right: 8px;
}
.name {
  font-weight: 600;
  font-size: 14px;
  color: #000000a7;
  display: flex;
  align-items: center;
  cursor: pointer;
}
.name:hover .edit-icon {
  opacity: 1;
}
.edit-icon {
  font-size: 14px;
  margin-left: 4px;
  color: #909399;
  opacity: 0;
  transition: opacity 0.3s;
}
.edit-name-input {
  width: 150px;
  .save-name-btn {
    cursor: pointer;
  }
}
.colleague-tag {
  margin-left: 5px;
}
.time {
  color: #b0b0b0;
  font-size: 13px;
}
.bottom-row {
  display: flex;
  align-items: center;
  margin-top: 2px;
}
.msg,
.voice {
  color: #888;
  font-size: 14px;
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.unread {
  background: #8e9fff;
  color: #fff;
  border-radius: 12px;
  font-size: 13px;
  min-width: 20px;
  text-align: center;
  padding: 0 7px;
  margin-left: 8px;
  line-height: 20px;
  height: 20px;
  display: inline-block;
}
.actions {
  margin-left: 10px;
  display: flex;
  gap: 10px;
}
.end-session-btn {
  margin-left: 10px;
}
.notification-settings {
  padding: 8px;
}
.notification-settings h4 {
  margin-top: 0;
  margin-bottom: 12px;
  font-size: 14px;
  color: #606266;
}
.setting-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}
.setting-item span {
  font-size: 14px;
  color: #606266;
}
.setting-tip {
  margin-top: 8px;
}
.status-online {
  color: #67c23a;
}
.status-offline {
  color: #909399;
}
</style>
